﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BitTorrentSharp.Helpers;

namespace BitTorrentSharp.KRPC.Messages
{
    /// <summary>
    /// Transaction
    /// </summary>
    public class Transaction : IEquatable<Transaction>
    {
        public Transaction(UInt16 id)
        {
            this._id = id;
        }

        public Transaction(byte[] id)
        {
            if (id == null)
                throw new ArgumentNullException("id");
            if (id.Length != 2)
                throw new ArgumentException("id's length must be two");
            // uint16
            this._id = BitConverter.ToUInt16(id, 0);
        }

        #region private
        /// <summary>
        /// id
        /// </summary>
        private UInt16 _id;

        #endregion

        /// <summary>
        /// Get byte array data
        /// </summary>
        /// <returns></returns>
        public byte[] ToArray()
        {
            return BitConverter.GetBytes(this._id);
        }
        /// <summary>
        /// Get next transaction id
        /// If meet the max transaction id, then, return the min transaction id
        /// </summary>
        /// <returns></returns>
        public Transaction MoveNext()
        {
            if (this._id == UInt16.MaxValue)
                return new Transaction(0);
            else
                return new Transaction((UInt16)(this._id + (UInt16)1));
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
            else if (obj is Transaction)
                return this.Equals(obj as Transaction);
            else
                return false;
        }

        public bool Equals(Transaction other)
        {
            if (other == null)
                return false;

            return this._id == other._id;
        }

        public override int GetHashCode()
        {
            return this._id.GetHashCode();
        }
    }
}
